package com.mcxx.modules.miniSalvation.salary.service.write;

import cn.hutool.core.bean.BeanUtil;
import com.mcxx.common.exception.BizException;
import com.mcxx.convert.FormulCountParamConvert;
import com.mcxx.formulcount.param.FormulCountParam;
import com.mcxx.formulcount.param.SecurityParam;
import com.mcxx.modules.miniSalvation.family.dao.write.FamilyMainWriteDao;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMainEntity;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMemberEntity;
import com.mcxx.modules.miniSalvation.family.service.write.FamilyMainWriteService;
import com.mcxx.modules.miniSalvation.family.service.write.FamilyMemberWriteService;
import com.mcxx.modules.miniSalvation.order.dto.ExOrderSalaryDTO;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.entity.OrderStateEntity;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.miniSalvation.order.service.write.OrderWriteService;
import com.mcxx.modules.miniSalvation.salary.dao.read.MemberSalaryReadDao;
import com.mcxx.modules.miniSalvation.salary.dto.*;
import com.mcxx.modules.formulcount.FormulCountService;
import com.mcxx.modules.miniSalvation.order.dao.read.OrderReadDao;
import com.mcxx.modules.miniSalvation.order.dao.write.OrderWriteDao;
import com.mcxx.modules.miniSalvation.order.dto.OrderSalaryDTO;
import com.mcxx.modules.miniSalvation.salary.dao.write.FamilySalaryWriteDao;
import com.mcxx.modules.miniSalvation.salary.dao.write.MemberSalaryWriteDao;
import com.mcxx.modules.miniSalvation.salary.entity.FamilySalaryEntity;
import com.mcxx.modules.miniSalvation.salary.entity.MemberSalaryEntity;
import com.mcxx.modules.miniSalvation.salary.service.read.FamilySalaryReadService;
import com.mcxx.result.BaseResult;
import com.mcxx.util.CommonUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service("familySalaryWriteService")
@TaTransactional
public class FamilySalaryWriteService {
    private static final Logger logger = LoggerFactory.getLogger(FamilySalaryWriteService.class);
    @Autowired
    private OrderReadDao orderReadDao;
    @Autowired
    private FamilySalaryWriteDao familySalaryWriteDao;
    @Autowired
    private FamilySalaryReadService familySalaryReadService;
    @Autowired
    private MemberSalaryWriteDao memberSalaryWriteDao;
    @Autowired
    private MemberSalaryReadDao memberSalaryReadDao;
    @Autowired
    private FamilyMainWriteDao familyMainWriteDao;
    @Autowired
    private FamilyMemberWriteService familyMemberWriteService;
    @Autowired
    private OrderWriteDao orderWriteDao;
    @Autowired
    private FormulCountService formulCountService;
    @Autowired
    private OrderReadService orderReadService;
    @Autowired
    private FamilyMainWriteService familyMainWriteService;
    @Autowired
    private OrderWriteService orderWriteService;




    public int inserts(List<FamilySalaryEntity> familySalaryList){
        return familySalaryWriteDao.inserts(familySalaryList);
    }


    public int batchDeleteByIds(List<String> familySalaryIds) {
        return familySalaryWriteDao.batchDeleteByIds(familySalaryIds);
    }


    public int insertIgnoreNull(FamilySalaryEntity familySalary){
        return familySalaryWriteDao.insertIgnoreNull(familySalary);
    }


    public int updateIgnoreNull(FamilySalaryEntity familySalary){
        return familySalaryWriteDao.updateIgnoreNull(familySalary);
    }




    public BaseResult salaryDT(OrderSalaryDTO orderSalaryParam, ExOrderSalaryDTO exOrderParam, UserAccountVo userAccountVo,int type,String businessType){
        String orderId;
        if(Constant.BusinessCode.DIBAO.equals(businessType)){
            orderId = orderSalaryParam.getOrderId();
        }else{
            orderId = exOrderParam.getOrderId();
        }


        OrderEntity orderEntity = orderReadService.getOrderById(orderId);
        String state = orderEntity.getState();
        logger.info("计算家庭救助待遇，orderId:{},state:{},type:{}", orderId,state,type);
        if(Constant.BizStateNew.APPROVE_YES.equals(state)||Constant.BizStateNew.APPROVE_REFUSE.equals(state)){
            throw new BizException("-1","该业务已审核完毕，请勿重复操作");
        }

        SaveFamilySalaryDTO saveFamilySalaryDTO;
        if(Constant.BusinessCode.DIBAO.equals(businessType)){
            saveFamilySalaryDTO = this.calcFmailySalaryDiBao(orderSalaryParam, userAccountVo);
        }else{

            saveFamilySalaryDTO = this.calcFmailySalaryTeKun(exOrderParam, userAccountVo);
        }
        saveFamilySalaryDTO.setBusinessType(businessType);


        if(type == 1){

            this.changeSalarySaveMember(businessType,orderSalaryParam,exOrderParam);
            return this.saveFamilySalaryDT(saveFamilySalaryDTO);
        }else{
            return this.changeFamilySalaryDT(saveFamilySalaryDTO);
        }
    }

    public void changeSalarySaveMember(String businessType,OrderSalaryDTO orderSalaryParam, ExOrderSalaryDTO exOrderParam){
        List<FamilyMemberSalaryDTO> changeMemberList = new ArrayList<>();
        String orderId = "";
        String familyId = "";
        if(Constant.BusinessCode.DIBAO.equals(businessType)){
            changeMemberList = orderSalaryParam.getMemberList();
            orderId = orderSalaryParam.getOrderId();
            familyId = orderSalaryParam.getFamilyId();
        }else{
            changeMemberList = exOrderParam.getMemberList();
            orderId = exOrderParam.getOrderId();
            familyId = exOrderParam.getFamilyId();
        }
        int count = 0;
        FamilyMainEntity family = new FamilyMainEntity();
        family.setId(familyId);
        for(FamilyMemberSalaryDTO m:changeMemberList){

            FamilyMemberEntity member = new FamilyMemberEntity();
            member.setId(m.getMemberId());
            member.setIsSaveObject(m.getIsSaveObject());
            familyMemberWriteService.updateFamilyMember(member);

            if("1".equals(m.getIsSaveObject())){
                count++;
            }

            if("0".equals(m.getIsSaveObject())){
                if("01".equals(m.getFamilyRelation())){
                    family.setMasterInSave("02");
                }
            }else{
                if("01".equals(m.getFamilyRelation())){
                    family.setMasterInSave("01");
                }
            }


        }
        family.setSaveMemberNumber(count);
        int i = familyMainWriteService.changeSaveMemberNumById(family);
        if(i <= 0){
            throw new BizException("-1", "修改家庭保障对象异常");
        }
        i = orderWriteService.changeSaveMemberNum(family.getSaveMemberNumber(), orderId);
        if(i <= 0){
            throw new BizException("-1", "修改业务保障对象异常");
        }







//                if(ms.getMemberId().equals(m.getMemberId()) && !ms.getIsSaveObject().equals(m.getIsSaveObject())){








    }


    public SaveFamilySalaryDTO calcFmailySalaryTeKun(ExOrderSalaryDTO exOrderSalaryParam, UserAccountVo userAccountVo){

        List<FamilyMemberSalaryDTO> viewMemberList = exOrderSalaryParam.getMemberList();

        ExOrderSalaryDTO orderSalaryDTO = orderReadDao.getExSalaryInfoById(exOrderSalaryParam.getOrderId());

        orderSalaryDTO.setStandType(exOrderSalaryParam.getStandType());

        orderSalaryDTO.setSupplyType(exOrderSalaryParam.getSupplyType());

        orderSalaryDTO.setSupplyOrgId(exOrderSalaryParam.getSupplyOrgId());
        long saveMemberNumber = exOrderSalaryParam.getMemberList().stream().mapToInt(t->Constant.IsSaveObject.YES.equals(t.getIsSaveObject()) ? 1 : 0).sum();
        if(saveMemberNumber<=0){
            throw new BizException("-1","至少有一个人纳入救助范围");
        }
        orderSalaryDTO.setSaveMemberNumber((int)saveMemberNumber);



        String parentOrgId = userAccountVo.getParentId();
        if(Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())){
            parentOrgId = userAccountVo.getOrgId();
        }
        FormulCountParam formulCountParam = FormulCountParamConvert.convertOrderSalaryDTO(orderSalaryDTO, parentOrgId);



        BigDecimal familySalaryTotal = new BigDecimal(0);

        String masterInSave = "01";

        double standardMoney = 0;

        BigDecimal sumFamilyBaseSalaryNumber = new BigDecimal(0), sumFamilyCareSalaryNumber = new BigDecimal(0);

        Map<String, FamilyMemberSalaryDTO> viewMemberMap = viewMemberList.stream().collect(Collectors.toMap(FamilyMemberSalaryDTO::getMemberId, a -> a,(k1, k2)->k1));
        List<FamilyMemberSalaryDTO> familyMemberList = memberSalaryReadDao.getMemberByFamilyId(orderSalaryDTO.getFamilyId(), null);
        List<SaveMemberSalaryDTO> memberSalaryList = new ArrayList<>();
        for(FamilyMemberSalaryDTO familyMemberSalary : familyMemberList){
            FamilyMemberSalaryDTO viewMember = viewMemberMap.get(familyMemberSalary.getMemberId());
            if(null != viewMember){
                familyMemberSalary.setIsSaveObject(viewMember.getIsSaveObject());
            }
            if(Constant.IsSaveObject.NO.equals(familyMemberSalary.getIsSaveObject())){
                continue;
            }
            if(Constant.DomesticRelation.ONESELF.equals(familyMemberSalary.getFamilyRelation())){

                masterInSave = Constant.IsSaveObject.NO.equals(familyMemberSalary.getIsSaveObject()) ? "02" : "01";
            }

            FormulCountParamConvert.convertMemberSalaryDTO(familyMemberSalary, formulCountParam);

            BaseResult<List<SecurityParam>> securityRst = formulCountService.exceptionalFormulCount(formulCountParam);

            if("300".equals(securityRst.getCode()) || "400".equals(securityRst.getCode())){
                throw new BizException("-1", securityRst.getMsg());
            }
            else if("0".equals(securityRst.getCode()) == false){

                throw new BizException("-1", securityRst.getMsg());
            }

            List<SecurityParam> securityList = securityRst.getData();
            if(securityList.size() <= 0){
                continue;
            }

            for(SecurityParam securityParam : securityList){

                standardMoney = securityParam.getStandardMoney();

                double memberSalaryNumber = Double.parseDouble(securityParam.getMoney());

                String itemType = "";

                if(("特困人员基本生活费").equals(securityParam.getMoneyName())){
                    //5.5.1、特困人员基本生活费
                    itemType = Constant.CareFeeType.TEKUN_BASE_CODE;
                    sumFamilyBaseSalaryNumber = sumFamilyBaseSalaryNumber.add(new BigDecimal(memberSalaryNumber)).setScale(2,RoundingMode.HALF_UP);
                } else {
                    //5.5.1、照料费
                    itemType = Constant.CareFeeType.CARE_CODE;
                    sumFamilyCareSalaryNumber = sumFamilyCareSalaryNumber.add(new BigDecimal(memberSalaryNumber)).setScale(2,RoundingMode.HALF_UP);
                }


                familySalaryTotal = familySalaryTotal.add(new BigDecimal(memberSalaryNumber)).setScale(2,RoundingMode.HALF_UP);
                //5.5.3、封装成员待遇参数
                MemberSalaryEntity memberSalaryEntity= FormulCountParamConvert.convertMemberSalaryEntity(orderSalaryDTO, familyMemberSalary, memberSalaryNumber, itemType);
                //5.5.4、保存
                SaveMemberSalaryDTO mSalary = new SaveMemberSalaryDTO();
                BeanUtils.copyProperties(memberSalaryEntity,mSalary);
                mSalary.setIsSaveObject(familyMemberSalary.getIsSaveObject());
                mSalary.setFamilyRelation(familyMemberSalary.getFamilyRelation());
                memberSalaryList.add(mSalary);

            }
        }



        FamilySalaryEntity familySalaryentity = FormulCountParamConvert.convertFamilySalaryEntity(orderSalaryDTO, familySalaryTotal.doubleValue(),
                masterInSave, sumFamilyBaseSalaryNumber.doubleValue(), sumFamilyCareSalaryNumber.doubleValue(), standardMoney);

        SaveFamilySalaryDTO fSalary = new SaveFamilySalaryDTO();
        BeanUtils.copyProperties(familySalaryentity,fSalary);
        exOrderSalaryParam.setFamilyId(fSalary.getFamilyId());


        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderId(orderSalaryDTO.getOrderId());
        orderEntity.setSalvMoney(familySalaryTotal.doubleValue());
        orderEntity.setBaseSalary(sumFamilyBaseSalaryNumber.doubleValue());
        orderEntity.setCareSalary(sumFamilyCareSalaryNumber.doubleValue());
        orderEntity.setEndMonth(Constant.MAX_YEAR);

        orderEntity.setStandType(exOrderSalaryParam.getStandType());

        orderEntity.setSupplyType(exOrderSalaryParam.getSupplyType());

        orderEntity.setSupplyOrgId(exOrderSalaryParam.getSupplyOrgId());
        if("01".equals(exOrderSalaryParam.getSupplyType())){
            orderEntity.setSupplyOrgName(exOrderSalaryParam.getSupplyOrgName());
        }else{
            orderEntity.setSupplyOrgName("");
        }
        SaveOrderSalaryDTO oSalary = new SaveOrderSalaryDTO();
        BeanUtils.copyProperties(orderEntity,oSalary);


        if(memberSalaryList.isEmpty() || BeanUtil.isEmpty(fSalary) || BeanUtil.isEmpty(oSalary)){

            throw new BizException("-1", "救助待遇计算错误，请联系管理员处理");
        }
        fSalary.setMemberSalaryList(memberSalaryList);
        fSalary.setSaveOrderSalaryDTO(oSalary);

        return fSalary;
    }


    public SaveFamilySalaryDTO calcFmailySalaryDiBao(OrderSalaryDTO orderSalaryParam, UserAccountVo userAccountVo){


        if(null == orderSalaryParam.getMemberList()){
            throw new BizException("-1", "成员对象列表为空");
        }
        List<FamilyMemberSalaryDTO> viewMemberList = orderSalaryParam.getMemberList();
        OrderSalaryDTO orderSalaryDTO = orderReadDao.getSalaryInfoById(orderSalaryParam.getOrderId());
        orderSalaryDTO.setStandType(orderSalaryParam.getStandType());
        orderSalaryDTO.setCountType(orderSalaryParam.getCountType());

        long saveMemberNumber = orderSalaryParam.getMemberList().stream().mapToInt(t->Constant.IsSaveObject.YES.equals(t.getIsSaveObject()) ? 1 : 0).sum();

        int saveMemberNumberInt= (int)saveMemberNumber;
        log.info("保障人数long:{},转int: {}",saveMemberNumber,saveMemberNumberInt);
        if(saveMemberNumberInt<=0){
            saveMemberNumberInt=1;
            log.info("保障人数修正为:1");
        }
        orderSalaryDTO.setSaveMemberNumber(saveMemberNumberInt);


        String parentOrgId = userAccountVo.getParentId();
        if(Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())){
            parentOrgId = userAccountVo.getAreaCode();
        }
        FormulCountParam formulCountParam = FormulCountParamConvert.convertOrderSalaryDTO(orderSalaryDTO, parentOrgId);
        if(null != orderSalaryParam.getFamilyRevenue()){

            if(orderSalaryParam.getFamilyRevenue().intValue() < 0){
                formulCountParam.setIncome(0d);
            }else{
                BigDecimal bigDecimal = new BigDecimal(orderSalaryParam.getFamilyRevenue());
                formulCountParam.setIncome(bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
            }
        }


        String masterSave = "01";


        BigDecimal memberSalaryTotal = new BigDecimal(0);

        BigDecimal sortSalaryTotal = new BigDecimal(0);

        double standardMoney = 0;


        Map<String, FamilyMemberSalaryDTO> viewMemberMap = viewMemberList.stream().collect(Collectors.toMap(FamilyMemberSalaryDTO::getMemberId, a -> a,(k1, k2)->k1));
        List<FamilyMemberSalaryDTO> familyMemberList = memberSalaryReadDao.getMemberByFamilyId(orderSalaryDTO.getFamilyId(), null);

        int index = 0;

        List<SaveMemberSalaryDTO> memberSalaryList = new ArrayList<>();
        for(FamilyMemberSalaryDTO familyMemberSalary : familyMemberList){
            FamilyMemberSalaryDTO viewMember = viewMemberMap.get(familyMemberSalary.getMemberId());
            if(null != viewMember){
                familyMemberSalary.setIsSaveObject(viewMember.getIsSaveObject());
            }
            if(Constant.IsSaveObject.NO.equals(familyMemberSalary.getIsSaveObject())){
                continue;
            }
            if(Constant.DomesticRelation.ONESELF.equals(familyMemberSalary.getFamilyRelation())){

                masterSave = Constant.IsSaveObject.NO.equals(familyMemberSalary.getIsSaveObject()) ? "02" : "01";
            }

            FormulCountParamConvert.convertMemberSalaryDTO(familyMemberSalary, formulCountParam);

            BaseResult<List<SecurityParam>> securityRst = null;

            if(Constant.SaveType.DRB.equals(orderSalaryParam.getFamilyObjectType())){

                formulCountParam.setSalaryNumber(viewMember.getBasicSalary());
                securityRst = formulCountService.drbFormulCount(formulCountParam);
            }else {
                securityRst = formulCountService.diBaoFormulCount(formulCountParam);
            }


            if("300".equals(securityRst.getCode()) || "400".equals(securityRst.getCode())){
                throw new BizException(securityRst.getCode(), securityRst.getMsg());
            }else if("0".equals(securityRst.getCode()) == false){

                throw new BizException(securityRst.getCode(), "没有找到符合救助该人员的政策！请您检查救助政策配置是否正确！");
            }

            List<SecurityParam> securityList = securityRst.getData();
            if(securityList.size() <= 0){
                continue;
            }

            for(SecurityParam securityParam : securityList){

                if(!CommonUtil.invalidArgs(securityParam.getStandardMoney())){
                    standardMoney = securityParam.getStandardMoney();
                }

                double memberSalaryNumber = Double.parseDouble(securityParam.getMoney());

                double remainder = 0d;

                String itemType = "";
                //5.5.1、基本就准金
                if("基本救助金".equals(securityParam.getMoneyName())){
                    //5.5.1.1、根据计算方式，得到家庭成员救助待遇
                    if("01".equals(securityParam.getSalvationTarget())){
                        //5.5.1.1.1、 按家庭计算 ,得到人均救助金额
                        BigDecimal money = new BigDecimal(securityParam.getMoney());
                        memberSalaryNumber = money.divide(new BigDecimal(formulCountParam.getSaveMemberNumber()),2,RoundingMode.HALF_UP).doubleValue();

                        remainder = money.subtract(new BigDecimal(memberSalaryNumber*formulCountParam.getSaveMemberNumber())).setScale(2,RoundingMode.HALF_UP).doubleValue();
                        if(index == 0){
                            memberSalaryNumber = new BigDecimal(memberSalaryNumber).add(new BigDecimal(remainder)).setScale(2,RoundingMode.HALF_UP).doubleValue() ;
                        }
                    }else if("02".equals(securityParam.getSalvationTarget())){
                        //5.5.1.1.1.2、按个人计算
                        memberSalaryNumber = Double.parseDouble(securityParam.getMoney());
                    }
                    itemType = Constant.CareFeeType.DIBAO_BASE_CODE;
                    //5.5.5、成员待遇总和，累加
                    memberSalaryTotal = memberSalaryTotal.add(new BigDecimal(memberSalaryNumber)).setScale(2,RoundingMode.HALF_UP);
                } else if("特殊救助金".equals(securityParam.getMoneyName())){
                    //5.5.2、特殊救助金
                    itemType = Constant.CareFeeType.DIBAO_SPECIAL_CODE;
                }else if("分类救助金".equals(securityParam.getMoneyName())){
                    //5.5.3、分类救助金
                    itemType = Constant.CareFeeType.DIBAO_FENLEI_CODE;
                    sortSalaryTotal = sortSalaryTotal.add(new BigDecimal(memberSalaryNumber)).setScale(2,RoundingMode.HALF_UP);
                }
                //5.5.3、封装成员待遇参数
                MemberSalaryEntity memberSalaryEntity = FormulCountParamConvert.convertMemberSalaryEntity(orderSalaryDTO, familyMemberSalary, memberSalaryNumber, itemType);
                //5.5.4、保存
                SaveMemberSalaryDTO mSalary = new SaveMemberSalaryDTO();
                BeanUtils.copyProperties(memberSalaryEntity,mSalary);
                mSalary.setIsSaveObject(familyMemberSalary.getIsSaveObject());
                mSalary.setFamilyRelation(familyMemberSalary.getFamilyRelation());
                memberSalaryList.add(mSalary);

//                //5.5.5、成员待遇总和，累加

            }
            index++;
        }



        FamilySalaryEntity familySalaryentity = FormulCountParamConvert.convertFamilySalaryEntity(orderSalaryDTO, memberSalaryTotal.doubleValue(),sortSalaryTotal.doubleValue(),
                masterSave, standardMoney);

        SaveFamilySalaryDTO fSalary = new SaveFamilySalaryDTO();
        BeanUtils.copyProperties(familySalaryentity,fSalary);
        orderSalaryParam.setFamilyId(fSalary.getFamilyId());


        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderId(orderSalaryDTO.getOrderId());
        orderEntity.setSalvMoney(memberSalaryTotal.add(sortSalaryTotal).setScale(2,RoundingMode.HALF_UP).doubleValue());
        orderEntity.setCountType(orderSalaryParam.getCountType());
        orderEntity.setEndMonth(Constant.MAX_YEAR);
        SaveOrderSalaryDTO oSalary = new SaveOrderSalaryDTO();
        BeanUtils.copyProperties(orderEntity,oSalary);
        oSalary.setBaseSalary(memberSalaryTotal.doubleValue());
        oSalary.setSortSalary(sortSalaryTotal.doubleValue());


        if(memberSalaryList.isEmpty() || BeanUtil.isEmpty(fSalary) || BeanUtil.isEmpty(oSalary)){

            throw new BizException("-1", "救助待遇计算错误，请确认是否保障对象已勾选至少一个为是");
        }
        fSalary.setMemberSalaryList(memberSalaryList);
        fSalary.setSaveOrderSalaryDTO(oSalary);

        return fSalary;
    }


    public BaseResult<Boolean> saveFamilySalaryDT(SaveFamilySalaryDTO salaryDto){
        BaseResult<Boolean> rstMsg = new BaseResult<>();
        rstMsg.setMsg("家庭救助待遇计算完成");
        rstMsg.setData(true);

        if(salaryDto.getMemberSalaryList().isEmpty() || BeanUtil.isEmpty(salaryDto) || BeanUtil.isEmpty(salaryDto.getSaveOrderSalaryDTO())){

            throw new BizException("-1", "救助待遇计算错误，请联系管理员处理");
        }

        List<SaveMemberSalaryDTO> memberSalaryList = salaryDto.getMemberSalaryList();
        SaveOrderSalaryDTO saveOrderSalaryDTO = salaryDto.getSaveOrderSalaryDTO();

        logger.info("删除之前的待遇信息，orderId:{}",saveOrderSalaryDTO.getOrderId());

        memberSalaryWriteDao.deleteByOrderIdAndSalaryType(saveOrderSalaryDTO.getOrderId());

        familySalaryWriteDao.deleteByOrderIdAndsalaryType(saveOrderSalaryDTO.getOrderId());

        for(SaveMemberSalaryDTO ms: memberSalaryList){
            MemberSalaryEntity memberSalaryEntity = new MemberSalaryEntity();
            BeanUtils.copyProperties(ms,memberSalaryEntity);
            int rst = memberSalaryWriteDao.insertIgnoreNull(memberSalaryEntity);
            if(rst <= 0){
                throw  new BizException("-1", "保存成员待遇异常，新增失败");
            }
        }
        FamilySalaryEntity familySalaryentity = new FamilySalaryEntity();
        BeanUtils.copyProperties(salaryDto,familySalaryentity);
        familySalaryentity.setId(Constant.getUUID());
        familySalaryWriteDao.insertIgnoreNull(familySalaryentity);

        OrderEntity orderEntity = new OrderEntity();
        BeanUtils.copyProperties(saveOrderSalaryDTO,orderEntity);
        int rst = orderWriteDao.updateIgnoreNull(orderEntity);
        if(rst <= 0){
            throw  new BizException("-1", "业务状态异常，修改失败");
        }


        this.saveReissueSalary(salaryDto);
        return rstMsg;
    }


    public BaseResult changeFamilySalaryDT(SaveFamilySalaryDTO salaryDto){

        if(salaryDto.getMemberSalaryList().isEmpty() || BeanUtil.isEmpty(salaryDto) || BeanUtil.isEmpty(salaryDto.getSaveOrderSalaryDTO())){

            throw new BizException("-1", "救助待遇计算错误，请联系管理员处理");
        }
        BaseResult res = new BaseResult();
        SaveOrderSalaryDTO orderDto = salaryDto.getSaveOrderSalaryDTO();
        Map<String, Object> rstMap = new HashMap<>();
        OrderSalaryDTO orderSalary = orderReadDao.getSalaryInfo(orderDto.getOrderId());
        orderSalary.setCountType(orderDto.getCountType());
        orderSalary.setEndMonth(orderDto.getEndMonth());
        orderSalary.setSalvMoney(orderDto.getSalvMoney());
        orderSalary.setSupplyType(orderDto.getSupplyType());
        orderSalary.setSupplyOrgId(orderDto.getSupplyOrgId());
        orderSalary.setBaseSalary(orderDto.getBaseSalary());
        orderSalary.setSortSalary(orderDto.getSortSalary());
        //orderSalary.setSupplyOrgName(orderDto.gets);
        rstMap.put("orderSalary", orderSalary);

        List<SaveMemberSalaryDTO> saveMemberList = salaryDto.getMemberSalaryList();
        Map<String, List<SaveMemberSalaryDTO>> saveMemberMap = saveMemberList.stream().collect(Collectors.groupingBy(SaveMemberSalaryDTO::getMemberId));

        //Map<String, SaveMemberSalaryDTO> saveMemberMap = saveMemberList.stream().collect(Collectors.toMap(SaveMemberSalaryDTO::getMemberId, a -> a,(k1, k2)->k1));
        List<MemberSalaryDTO> returnMemberList = null;
        if(Constant.OrderType.RECHECK.equals(orderSalary.getType())){
            returnMemberList = memberSalaryReadDao.listMemberSalaryRecheck(orderSalary.getFamilyId(), orderDto.getOrderId(), null);
        }else {
            returnMemberList = memberSalaryReadDao.listMemberSalary(orderSalary.getFamilyId(), orderDto.getOrderId(), null);
        }

        for(MemberSalaryDTO m: returnMemberList){

            List<SaveMemberSalaryDTO> saveMember = saveMemberMap.get(m.getMemberId());
            if(null != saveMember){
                if(Constant.BusinessCode.DIBAO.equals(salaryDto.getBusinessType())){
                    m.setIsSaveObject("1");
                    m.setItemType(saveMember.get(0).getItemType());
                    if(saveMember.size()>0){
                        Double salaryNumber = 0d;
                        for(SaveMemberSalaryDTO sm:saveMember){
                            if(Constant.CareFeeType.DIBAO_BASE_CODE.equals(sm.getItemType())){
                                m.setBasicSalary(sm.getSalaryNumber());
                            }
                            if(Constant.CareFeeType.DIBAO_FENLEI_CODE.equals(sm.getItemType())){
                                m.setSortSalary(sm.getSalaryNumber()+(m.getSortSalary()==null?0:m.getSortSalary()));
                            }
                            salaryNumber += sm.getSalaryNumber();
                        }
                        m.setSalaryNumber(salaryNumber);
                    }
                }else{
                    m.setIsSaveObject("1");
                    String basic = "";
                    String nursing = "";
                    for(SaveMemberSalaryDTO sm:saveMember){
                        if(Constant.CapitalFundPayCostType.BASIC.equals(sm.getItemType())){
                            basic = "基本生活费:"+sm.getSalaryNumber()+"元";
                        }

                    }
                    String aa = basic+"\n" +"   " +
                            "   "+nursing;
                    m.setSalaryBelong(aa);
                }

            }else{
                m.setIsSaveObject("0");
                m.setSalaryNumber(null);
                m.setItemType("");
                m.setSalaryBelong(null);
                m.setSortSalary(null);
                m.setBasicSalary(null);
            }
        }
        rstMap.put("memberSalaryList", returnMemberList);
        res.setData(rstMap);
        return res;
    }


    public BaseResult<Boolean> saveFamilySalaryDiBao(OrderSalaryDTO orderSalaryParam, UserAccountVo userAccountVo){
        BaseResult<Boolean> rstMsg = new BaseResult<>();
        rstMsg.setMsg("家庭救助待遇计算完成");
        rstMsg.setData(true);


        OrderSalaryDTO orderSalaryDTO = orderReadDao.getSalaryInfoById(orderSalaryParam.getOrderId());
        orderSalaryDTO.setStandType(orderSalaryParam.getStandType());
        orderSalaryDTO.setCountType(orderSalaryParam.getCountType());


        if(CommonUtil.invalidArgs(orderSalaryDTO.getSaveMemberNumber()) || orderSalaryDTO.getSaveMemberNumber() <= 0){
            throw new BizException("-1", "[" + orderSalaryDTO.getIdcard() + "]家庭无成员为保障对象");
        }

        String parentOrgId = userAccountVo.getParentId();
        if(Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())){
            parentOrgId = userAccountVo.getOrgId();
        }
        FormulCountParam formulCountParam = FormulCountParamConvert.convertOrderSalaryDTO(orderSalaryDTO, parentOrgId);
        if(null != orderSalaryParam.getFamilyRevenue()){

            if(orderSalaryParam.getFamilyRevenue().intValue() < 0){
                formulCountParam.setIncome(0d);
            }else{
                BigDecimal bigDecimal = new BigDecimal(orderSalaryParam.getFamilyRevenue());
                formulCountParam.setIncome(bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
            }
        }



        memberSalaryWriteDao.deleteByOrderIdAndSalaryType(orderSalaryParam.getOrderId());

        familySalaryWriteDao.deleteByOrderIdAndsalaryType(orderSalaryParam.getOrderId());


        String masterSave = "01";

        BigDecimal memberSalaryTotal = new BigDecimal(0);

        BigDecimal sortSalaryTotal = new BigDecimal(0);

        double standardMoney = 0;

        List<FamilyMemberSalaryDTO> familyMemberList = memberSalaryReadDao.getMemberByFamilyId(orderSalaryDTO.getFamilyId(), Constant.IsSaveObject.YES);

        int index = 0;
        for(FamilyMemberSalaryDTO familyMemberSalary : familyMemberList){
            if(Constant.DomesticRelation.ONESELF.equals(familyMemberSalary.getFamilyRelation())){

                masterSave = Constant.IsSaveObject.NO.equals(familyMemberSalary.getIsSaveObject()) ? "02" : "01";
            }

            FormulCountParamConvert.convertMemberSalaryDTO(familyMemberSalary, formulCountParam);

            BaseResult<List<SecurityParam>> securityRst = formulCountService.diBaoFormulCount(formulCountParam);

            if("300".equals(securityRst.getCode()) || "400".equals(securityRst.getCode())){
                throw new BizException(securityRst.getCode(), securityRst.getMsg());
            }else if("0".equals(securityRst.getCode()) == false){

                throw new BizException(securityRst.getCode(), "没有找到符合救助该人员的政策！请您检查救助政策配置是否正确！");
            }

            List<SecurityParam> securityList = securityRst.getData();
            if(securityList.size() <= 0){
                continue;
            }

            for(SecurityParam securityParam : securityList){

                standardMoney = securityParam.getStandardMoney();

                double memberSalaryNumber = Double.parseDouble(securityParam.getMoney());

                double remainder = 0d;

                String itemType = "";
                //5.5.1、基本就准金
                if("基本救助金".equals(securityParam.getMoneyName())){
                    //5.5.1.1、根据计算方式，得到家庭成员救助待遇
                    if("01".equals(securityParam.getSalvationTarget())){
                        //5.5.1.1.1、 按家庭计算 ,得到人均救助金额
                        BigDecimal money = new BigDecimal(securityParam.getMoney());
                        memberSalaryNumber = money.divide(new BigDecimal(formulCountParam.getSaveMemberNumber()),2,RoundingMode.HALF_UP).doubleValue();;

                        remainder = money.subtract(new BigDecimal(memberSalaryNumber*formulCountParam.getSaveMemberNumber())).setScale(2,RoundingMode.HALF_UP).doubleValue();
                        if(index == 0){
                            memberSalaryNumber = new BigDecimal(memberSalaryNumber).add(new BigDecimal(remainder)).setScale(2,RoundingMode.HALF_UP).doubleValue() ;
                        }
                        memberSalaryTotal = memberSalaryTotal.add(new BigDecimal(memberSalaryNumber));
                    }else if("02".equals(securityParam.getSalvationTarget())){
                        //5.5.1.1.1.2、按个人计算
                        memberSalaryNumber = Double.parseDouble(securityParam.getMoney());
                    }
                    itemType = Constant.CareFeeType.DIBAO_BASE_CODE;
                } else if("特殊救助金".equals(securityParam.getMoneyName())){
                    //5.5.2、特殊救助金
                    itemType = Constant.CareFeeType.DIBAO_SPECIAL_CODE;
                }else if("分类救助金".equals(securityParam.getMoneyName())){
                    //5.5.3、分类救助金
                    itemType = Constant.CareFeeType.DIBAO_FENLEI_CODE;
                    sortSalaryTotal = sortSalaryTotal.add(new BigDecimal(memberSalaryNumber));
                }
                //5.5.3、封装成员待遇参数
                MemberSalaryEntity memberSalaryEntity = FormulCountParamConvert.convertMemberSalaryEntity(orderSalaryDTO, familyMemberSalary, memberSalaryNumber, itemType);
                //5.5.4、保存
                memberSalaryWriteDao.insertIgnoreNull(memberSalaryEntity);
                //5.5.5、成员待遇总和，累加

            }
            index++;
        }



        FamilySalaryEntity familySalaryentity = FormulCountParamConvert.convertFamilySalaryEntity(orderSalaryDTO, memberSalaryTotal.doubleValue(),sortSalaryTotal.doubleValue(),
                masterSave, standardMoney);

        familySalaryWriteDao.insertIgnoreNull(familySalaryentity);


        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderId(orderSalaryDTO.getOrderId());
        orderEntity.setSalvMoney(memberSalaryTotal.doubleValue()+sortSalaryTotal.doubleValue());
        orderEntity.setCountType(orderSalaryParam.getCountType());
        orderEntity.setEndMonth(Constant.MAX_YEAR);
        int rst = orderWriteDao.updateIgnoreNull(orderEntity);
        if(rst <= 0){
            throw  new BizException("-1", "业务状态异常，修改失败");
        }
        return rstMsg;
    }


    public void copySalaryByOrderId(String orderId, String newOrderId, String curMonth) {
        int rows = familySalaryWriteDao.copySalaryByOrderId(orderId,newOrderId,curMonth);
        if (rows < 1) {
            throw new BizException(FailureCode.ERR_9999);
        }
    }


    public BaseResult<Boolean> confirmFamilySalaryDiBao(OrderSalaryDTO orderSalaryParam, Map<String, String> familyMemberMapParam,
                                                        int familySaveMemberObject, UserAccountVo userAccountVo){
        BaseResult<Boolean> rstMsg = new BaseResult<>();
        rstMsg.setMsg("家庭救助待遇计算完成");
        rstMsg.setData(true);



        OrderSalaryDTO orderSalaryDTO = orderReadDao.getSalaryInfoById(orderSalaryParam.getOrderId());

        orderSalaryDTO.setStandType(orderSalaryParam.getStandType());

        orderSalaryDTO.setCountType(orderSalaryParam.getCountType());

        orderSalaryDTO.setSaveMemberNumber(familySaveMemberObject);


        String parentOrgId = userAccountVo.getParentId();
        if(Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())){
            parentOrgId = userAccountVo.getOrgId();
        }
        FormulCountParam formulCountParam = FormulCountParamConvert.convertOrderSalaryDTO(orderSalaryDTO, parentOrgId);
        if(null != orderSalaryParam.getFamilyRevenue()){

            if(orderSalaryParam.getFamilyRevenue().intValue() < 0){
                formulCountParam.setIncome(0d);
            }else{
                BigDecimal bigDecimal = new BigDecimal(orderSalaryParam.getFamilyRevenue());
                formulCountParam.setIncome(bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
            }
        }



        memberSalaryWriteDao.deleteByOrderIdAndSalaryType(orderSalaryParam.getOrderId());

        familySalaryWriteDao.deleteByOrderIdAndsalaryType(orderSalaryParam.getOrderId());


        BigDecimal memberSalaryTotal = new BigDecimal(0);

        BigDecimal sortSalaryTotal = new BigDecimal(0);

        String masterInSave = "01";

        double standardMoney = 0;

        List<FamilyMemberSalaryDTO> familyMemberList = memberSalaryReadDao.getMemberByFamilyId(orderSalaryDTO.getFamilyId(), null);
        int index = 0;
        for(FamilyMemberSalaryDTO familyMemberSalary : familyMemberList){

            if(Constant.DomesticRelation.ONESELF.equals(familyMemberSalary.getFamilyRelation())){

                masterInSave = Constant.IsSaveObject.NO.equals(familyMemberMapParam.get(familyMemberSalary.getMemberId())) ? "02" : "01";
            }
            familyMemberWriteService.updateIsSaveObject(familyMemberSalary.getMemberId(), familyMemberMapParam.get(familyMemberSalary.getMemberId()));
            if(Constant.IsSaveObject.NO.equals(familyMemberMapParam.get(familyMemberSalary.getMemberId()))){

                continue;
            }

            familyMemberSalary.setIsSaveObject(familyMemberMapParam.get(familyMemberSalary.getMemberId()));

            FormulCountParamConvert.convertMemberSalaryDTO(familyMemberSalary, formulCountParam);

            BaseResult<List<SecurityParam>> securityRst = formulCountService.diBaoFormulCount(formulCountParam);

            if("300".equals(securityRst.getCode()) || "400".equals(securityRst.getCode())){
                throw new BizException(securityRst.getCode(), securityRst.getMsg());
            }else if("0".equals(securityRst.getCode()) == false){

                throw new BizException(securityRst.getCode(), "没有找到符合救助该人员的政策！请您检查救助政策配置是否正确！");
            }

            List<SecurityParam> securityList = securityRst.getData();
            if(securityList.size() <= 0){
                continue;
            }

            for(SecurityParam securityParam : securityList){

                standardMoney = securityParam.getStandardMoney();

                double memberSalaryNumber = Double.parseDouble(securityParam.getMoney());

                double remainder = 0d;

                String itemType = "";
                //4.7.1、基本就准金
                if("基本救助金".equals(securityParam.getMoneyName())){
                    //4.7.1.1、根据计算方式，得到家庭成员救助待遇
                    if("01".equals(securityParam.getSalvationTarget())){
                        //4.7.1.1.1、 按家庭计算
                        BigDecimal money = new BigDecimal(securityParam.getMoney());
                        memberSalaryNumber = money.divide(new BigDecimal(formulCountParam.getSaveMemberNumber()),2,RoundingMode.HALF_UP).doubleValue();

                        remainder = money.subtract(new BigDecimal(memberSalaryNumber*formulCountParam.getSaveMemberNumber())).setScale(2,RoundingMode.HALF_UP).doubleValue();
                        if(index == 0){
                            memberSalaryNumber = new BigDecimal(memberSalaryNumber).add(new BigDecimal(remainder)).setScale(2,RoundingMode.HALF_UP).doubleValue() ;
                        }
                        memberSalaryTotal = memberSalaryTotal.add(new BigDecimal(memberSalaryNumber)).setScale(2,RoundingMode.HALF_UP);
                    }else if("02".equals(securityParam.getSalvationTarget())){
                        //4.7.1.1.1.2、按个人计算
                        memberSalaryNumber = Double.parseDouble(securityParam.getMoney());
                    }
                    itemType = Constant.CareFeeType.DIBAO_BASE_CODE;
                } else if("特殊救助金".equals(securityParam.getMoneyName())){
                    //4.7.1.2、特殊救助金
                    itemType = Constant.CareFeeType.DIBAO_SPECIAL_CODE;
                }else if("分类救助金".equals(securityParam.getMoneyName())){
                    //4.7.1.3、分类救助金
                    itemType = Constant.CareFeeType.DIBAO_FENLEI_CODE;
                    sortSalaryTotal = sortSalaryTotal.add(new BigDecimal(memberSalaryNumber));
                }


                //4.7.3、封装成员待遇参数
                MemberSalaryEntity memberSalaryEntity= FormulCountParamConvert.convertMemberSalaryEntity(orderSalaryDTO, familyMemberSalary, memberSalaryNumber, itemType);
                //4.7.4、保存
                memberSalaryWriteDao.insertIgnoreNull(memberSalaryEntity);
            }
            index++;
        }



        FamilySalaryEntity familySalaryentity = FormulCountParamConvert.convertFamilySalaryEntity(orderSalaryDTO, memberSalaryTotal.doubleValue(),sortSalaryTotal.doubleValue(), masterInSave, standardMoney);

        familySalaryWriteDao.insertIgnoreNull(familySalaryentity);



        int rst = familyMainWriteDao.updateSaveMemberById(orderSalaryDTO.getFamilyId(), familySaveMemberObject, masterInSave);
        if(rst <= 0){
            throw new BizException("-1", "更新家庭待遇信息失败");
        }

        OrderStateEntity orderStateEntity = new OrderStateEntity(orderSalaryDTO.getOrderId(),
                null, null,
                null, null, orderSalaryParam.getCountType(), memberSalaryTotal.doubleValue()+sortSalaryTotal.doubleValue(),
                familySaveMemberObject);

        rst = orderWriteDao.updateState(orderStateEntity);
        if(rst <= 0){
            throw  new BizException("业务状态异常，修改失败");
        }

        return rstMsg;
    }


    public void batchChangeExpireDate(Map<String, Object> map) {
        familySalaryWriteDao.batchChangeExpireDate(map);
    }


    public void deleteByCustomFundPayId(List<String> customFundPayIdList){
        memberSalaryWriteDao.deleteByCustomFundPayId(customFundPayIdList);

        familySalaryWriteDao.deleteByCustomFundPayId(customFundPayIdList);
    }


    public int deleteSalaryByOrderId(String orderId) {
        memberSalaryWriteDao.deleteMemberSalaryByOrderId(orderId);
        return familyMainWriteDao.deleteFmySalaryByOrderId(orderId);
    }


    public int updateStartDate(String orderId, String startDate) {

        logger.info("修改待遇开始时间，orderId:{},startDate:{}",orderId,startDate);
        int rst = familySalaryWriteDao.updateStartDate(orderId,startDate);
        if(rst <= 0){
            throw new BizException("-1", "待遇开始时间修改失败");
        }
        rst = memberSalaryWriteDao.updateStartDate(orderId, startDate);
        if(rst <= 0){
            throw new BizException("-1", "待遇开始时间修改失败");
        }
        return 1;
    }


    public int updateEndDate(String orderId, String endDate) {
        int rst = familySalaryWriteDao.updateEndDate(orderId, endDate);
        if(rst <= 0){
            throw new BizException("-1", "待遇结束时间修改失败");
        }
        rst = memberSalaryWriteDao.updateEndDate(orderId, endDate);
        if(rst <= 0){
            throw new BizException("-1", "待遇结束时间修改失败");
        }
        return 1;
    }







    public BaseResult<Boolean> saveFamilySalaryTeKun(ExOrderSalaryDTO exOrderSalaryParam, UserAccountVo userAccountVo){
        BaseResult<Boolean> rstMsg = new BaseResult<>();
        rstMsg.setMsg("家庭救助待遇计算完成");
        rstMsg.setData(true);


        ExOrderSalaryDTO orderSalaryDTO = orderReadDao.getExSalaryInfoById(exOrderSalaryParam.getOrderId());

        orderSalaryDTO.setStandType(exOrderSalaryParam.getStandType());

        orderSalaryDTO.setSupplyType(exOrderSalaryParam.getSupplyType());

        orderSalaryDTO.setSupplyOrgId(exOrderSalaryParam.getSupplyOrgId());


        if(CommonUtil.invalidArgs(orderSalaryDTO.getSaveMemberNumber()) || orderSalaryDTO.getSaveMemberNumber() <= 0){
            log.info("[{},{}]家庭无成员为保障对象",orderSalaryDTO.getFamilyId(), orderSalaryDTO.getName());
            throw new BizException("-1", "[" + orderSalaryDTO.getIdcard() + "]家庭无成员为保障对象");
        }


        String parentOrgId = userAccountVo.getParentId();
        if(Constant.UserLevel.COUNTY.equals(userAccountVo.getAreaLevel())){
            parentOrgId = userAccountVo.getOrgId();
        }
        FormulCountParam formulCountParam = FormulCountParamConvert.convertOrderSalaryDTO(orderSalaryDTO, parentOrgId);



        memberSalaryWriteDao.deleteByOrderIdAndSalaryType(exOrderSalaryParam.getOrderId());

        familySalaryWriteDao.deleteByOrderIdAndsalaryType(exOrderSalaryParam.getOrderId());



        BigDecimal familySalaryTotal = new BigDecimal(0);

        String masterInSave = "01";

        double standardMoney = 0;

        BigDecimal sumFamilyBaseSalaryNumber = new BigDecimal(0), sumFamilyCareSalaryNumber = new BigDecimal(0);

        List<FamilyMemberSalaryDTO> familyMemberList = memberSalaryReadDao.getMemberByFamilyId(orderSalaryDTO.getFamilyId(), Constant.IsSaveObject.YES);
        for(FamilyMemberSalaryDTO familyMemberSalary : familyMemberList){
            if(Constant.DomesticRelation.ONESELF.equals(familyMemberSalary.getFamilyRelation())){

                masterInSave = Constant.IsSaveObject.NO.equals(familyMemberSalary.getIsSaveObject()) ? "02" : "01";
            }

            FormulCountParamConvert.convertMemberSalaryDTO(familyMemberSalary, formulCountParam);

            BaseResult<List<SecurityParam>> securityRst = formulCountService.exceptionalFormulCount(formulCountParam);

            if("300".equals(securityRst.getCode()) || "400".equals(securityRst.getCode())){
                throw new BizException("-1", securityRst.getMsg());
            }else if("0".equals(securityRst.getCode()) == false){

                throw new BizException("-1", "没有找到符合救助该人员的政策！请您检查救助政策配置是否正确！");
            }

            List<SecurityParam> securityList = securityRst.getData();
            if(securityList.size() <= 0){
                continue;
            }

            for(SecurityParam securityParam : securityList){

                standardMoney = securityParam.getStandardMoney();

                double memberSalaryNumber = Double.parseDouble(securityParam.getMoney());

                String itemType = "";

                if(("特困人员基本生活费").equals(securityParam.getMoneyName())){
                    //5.5.1、特困人员基本生活费
                    itemType = Constant.CareFeeType.TEKUN_BASE_CODE;
                    sumFamilyBaseSalaryNumber = sumFamilyBaseSalaryNumber.add(new BigDecimal(memberSalaryNumber));
                } else {
                    //5.5.1、照料费
                    itemType = Constant.CareFeeType.CARE_CODE;
                    sumFamilyCareSalaryNumber = sumFamilyCareSalaryNumber.add(new BigDecimal(memberSalaryNumber));
                }


                familySalaryTotal = familySalaryTotal.add(new BigDecimal(memberSalaryNumber));
                //5.5.3、封装成员待遇参数
                MemberSalaryEntity memberSalaryEntity= FormulCountParamConvert.convertMemberSalaryEntity(orderSalaryDTO, familyMemberSalary, memberSalaryNumber, itemType);
                //5.5.4、保存
                memberSalaryWriteDao.insertIgnoreNull(memberSalaryEntity);
            }
        }



        FamilySalaryEntity familySalaryentity = FormulCountParamConvert.convertFamilySalaryEntity(orderSalaryDTO, familySalaryTotal.doubleValue(),
                masterInSave, sumFamilyBaseSalaryNumber.doubleValue(), sumFamilyCareSalaryNumber.doubleValue(), standardMoney);

        familySalaryWriteDao.insertIgnoreNull(familySalaryentity);


        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderId(orderSalaryDTO.getOrderId());
        orderEntity.setSalvMoney(familySalaryTotal.doubleValue());
        orderEntity.setBaseSalary(sumFamilyBaseSalaryNumber.doubleValue());
        orderEntity.setCareSalary(sumFamilyCareSalaryNumber.doubleValue());
        orderEntity.setEndMonth(Constant.MAX_YEAR);

        orderEntity.setStandType(exOrderSalaryParam.getStandType());

        orderEntity.setSupplyType(exOrderSalaryParam.getSupplyType());

        orderEntity.setSupplyOrgId(exOrderSalaryParam.getSupplyOrgId());
        int rst = orderWriteDao.updateIgnoreNull(orderEntity);
        if(rst <= 0){
            throw  new BizException("-1", "业务状态异常，修改失败");
        }
        return rstMsg;
    }


    public BaseResult<Boolean> confirmFamilySalaryTeKun(ExOrderSalaryDTO exOrderSalaryParam, Map<String, String> familyMemberMapParam,
                                                        int familySaveMemberObject, UserAccountVo userAccountVo){
        BaseResult<Boolean> rstMsg = new BaseResult<>();
        rstMsg.setMsg("家庭救助待遇计算完成");
        rstMsg.setData(true);



        ExOrderSalaryDTO orderSalaryDTO = orderReadDao.getExSalaryInfoById(exOrderSalaryParam.getOrderId());

        orderSalaryDTO.setStandType(exOrderSalaryParam.getStandType());

        orderSalaryDTO.setSupplyType(exOrderSalaryParam.getSupplyType());

        orderSalaryDTO.setSupplyOrgId(exOrderSalaryParam.getSupplyOrgId());

        orderSalaryDTO.setSaveMemberNumber(familySaveMemberObject);



        memberSalaryWriteDao.deleteByOrderIdAndSalaryType(exOrderSalaryParam.getOrderId());

        familySalaryWriteDao.deleteByOrderIdAndsalaryType(exOrderSalaryParam.getOrderId());



        FormulCountParam formulCountParam = FormulCountParamConvert.convertOrderSalaryDTO(orderSalaryDTO, userAccountVo.getOrgId());


        BigDecimal memberSalaryTotal = new BigDecimal(0);


        String masterInSave = "01";

        double standardMoney = 0;

        BigDecimal sumBaseSalaryNumber = new BigDecimal(0), sumCareSalaryNumber = new BigDecimal(0);

        List<FamilyMemberSalaryDTO> familyMemberList = memberSalaryReadDao.getMemberByFamilyId(orderSalaryDTO.getFamilyId(), null);
        for(FamilyMemberSalaryDTO familyMemberSalary : familyMemberList){

            if(Constant.DomesticRelation.ONESELF.equals(familyMemberSalary.getFamilyRelation())){

                masterInSave = Constant.IsSaveObject.NO.equals(familyMemberMapParam.get(familyMemberSalary.getMemberId())) ? "02" : "01";
            }
            if("0".equals(familyMemberMapParam.get(familyMemberSalary.getMemberId()))){

                familyMemberWriteService.updateIsSaveObject(familyMemberSalary.getMemberId(), familyMemberMapParam.get(familyMemberSalary.getMemberId()));
                continue;
            }

            familyMemberSalary.setIsSaveObject(familyMemberMapParam.get(familyMemberSalary.getMemberId()));

            FormulCountParamConvert.convertMemberSalaryDTO(familyMemberSalary, formulCountParam);

            BaseResult<List<SecurityParam>> securityRst = formulCountService.exceptionalFormulCount(formulCountParam);

            if("300".equals(securityRst.getCode()) || "400".equals(securityRst.getCode())){
                throw new BizException(securityRst.getCode(), securityRst.getMsg());
            }else if("0".equals(securityRst.getCode()) == false){

                throw new BizException(securityRst.getCode(), "没有找到符合救助该人员的政策！请您检查救助政策配置是否正确！");
            }

            List<SecurityParam> securityList = securityRst.getData();
            if(securityList.size() <= 0){
                continue;
            }

            for(SecurityParam securityParam : securityList){

                standardMoney = securityParam.getStandardMoney();

                double memberSalaryNumber = Double.parseDouble(securityParam.getMoney());

                String itemType = "";

                if(("特困人员基本生活费").equals(securityParam.getMoneyName())){
                    //5.5.1、特困人员基本生活费
                    itemType = Constant.CareFeeType.TEKUN_BASE_CODE;
                    sumBaseSalaryNumber = sumBaseSalaryNumber.add(new BigDecimal(memberSalaryNumber));
                } else {
                    //5.5.1、照料费
                    itemType = Constant.CareFeeType.CARE_CODE;
                    sumCareSalaryNumber = sumCareSalaryNumber.add(new BigDecimal(memberSalaryNumber));
                }


                memberSalaryTotal = memberSalaryTotal.add(new BigDecimal(memberSalaryNumber));
                //5.5.3、封装成员待遇参数
                MemberSalaryEntity memberSalaryEntity= FormulCountParamConvert.convertMemberSalaryEntity(orderSalaryDTO, familyMemberSalary, memberSalaryNumber, itemType);
                //5.5.4、保存
                memberSalaryWriteDao.insertIgnoreNull(memberSalaryEntity);
            }
        }



        FamilySalaryEntity familySalaryentity = FormulCountParamConvert.convertFamilySalaryEntity(orderSalaryDTO, memberSalaryTotal.doubleValue(),
                masterInSave, sumBaseSalaryNumber.doubleValue(), sumCareSalaryNumber.doubleValue(), standardMoney);

        familySalaryWriteDao.insertIgnoreNull(familySalaryentity);



        int rst = familyMainWriteDao.updateSaveMemberById(orderSalaryDTO.getFamilyId(), familySaveMemberObject, masterInSave);
        if(rst <= 0){
            throw new BizException("-1", "更新家庭待遇信息失败");
        }


        OrderStateEntity orderStateEntity = new OrderStateEntity(orderSalaryDTO.getOrderId(),
                null, null,
                null, null, exOrderSalaryParam.getSupplyType(), exOrderSalaryParam.getSupplyOrgId(), memberSalaryTotal.doubleValue(),
                familySaveMemberObject);


        orderStateEntity.setCareSalary(sumCareSalaryNumber.doubleValue());
        orderStateEntity.setBaseSalary(sumBaseSalaryNumber.doubleValue());

        rst = orderWriteDao.updateState(orderStateEntity);
        if(rst <= 0){
            throw  new BizException("业务状态异常，修改失败");
        }

        return rstMsg;
    }




    public void saveReissueSalary(SaveFamilySalaryDTO familySalaryDTO) {
        String orderId = familySalaryDTO.getOrderId();
        String familyId = familySalaryDTO.getFamilyId();
        List<SaveMemberSalaryDTO> saveMemberList = familySalaryDTO.getMemberSalaryList();

        familySalaryWriteDao.deleteBufaSalaryByOrderId(orderId);
        memberSalaryWriteDao.deleteBufaSalaryByOrderId(orderId);

        Set<String> memberIdSet = new TreeSet<>();
        saveMemberList.stream().forEach(i -> memberIdSet.add(i.getMemberId()));


        Date salaryDate = new Date();

        Map<String, Double> bufaTypeNumber = new HashMap<>();
        List<MemberSalaryEntity> allMemberBufaSalaryList = new ArrayList<>();
        Iterator<String> memberIdIterator = memberIdSet.iterator();
        while(memberIdIterator.hasNext()){
            Map<String, String> params = new HashMap<>();
            params.put("familyId", familyId);
            params.put("memberId", memberIdIterator.next());
            List<MemberSalaryEntity> list = memberSalaryReadDao.selectMemberBufaSalaryCurrMonth(params);
            if(null!=list && list.size()>0) {
                for(MemberSalaryEntity entity : list) {

                    Double salaryNumber = bufaTypeNumber.get(entity.getSalaryType());
                    if(null == salaryNumber) {
                        salaryNumber = entity.getSalaryNumber();
                    }
                    else {
                        salaryNumber += entity.getSalaryNumber();
                    }
                    bufaTypeNumber.put(entity.getSalaryType(), salaryNumber);

                    salaryDate = entity.getStartDate();
                    entity.setId(Constant.getUUID());
                    entity.setOrderId(orderId);
                    entity.setUpdateDate(new Date());
                    entity.setRemark("保留本月的补发待遇");
                    allMemberBufaSalaryList.add(entity);
                }
            }
        }

        logger.info("本月待生成的成员补发待遇数记录为：{}", allMemberBufaSalaryList);
        if(allMemberBufaSalaryList.size() > 0) {
            memberSalaryWriteDao.insertBachSalary(allMemberBufaSalaryList);
        }


        logger.info("本月待生成的家庭补发待遇记录：{}", bufaTypeNumber);
        List<FamilySalaryEntity> familySalaryEntityList = new ArrayList<>();
        Iterator<String> iterator = bufaTypeNumber.keySet().iterator();
        while(iterator.hasNext()) {
            String salaryType = iterator.next();
            double familyBufaSalary = bufaTypeNumber.get(salaryType);
            FamilySalaryEntity familySalaryEntity = new FamilySalaryEntity();
            BeanUtils.copyProperties(familySalaryDTO, familySalaryEntity);
            familySalaryEntity.setId(Constant.getUUID());
            familySalaryEntity.setSalaryNumber(familyBufaSalary);
            familySalaryEntity.setStartDate(salaryDate);
            familySalaryEntity.setSalaryType(salaryType);
            familySalaryEntity.setEndDate(salaryDate);
            familySalaryEntity.setCreateTime(new Date());
            familySalaryEntity.setUpdateTime(new Date());
            familySalaryEntity.setInputDate(DateUtil.formatDate(new Date(), "yyyyMM"));
            familySalaryEntity.setRemark("保留本月的补发待遇");
            familySalaryEntityList.add(familySalaryEntity);
        }
        if(familySalaryEntityList.size() > 0) {
            familySalaryWriteDao.inserts(familySalaryEntityList);
        }
    }

    public void deleteFamilySalaryByOrderId(String orderId){
        int count = familySalaryReadService.selectCountByOrderId(orderId);
        if(count>0){
           this.deleteSalaryByOrderId(orderId);
        }
    }
}
